#include "ratingviewwidget.h"
#include <QApplication>
#include <QMenu>
#include <QDateTime>
#include <QDebug>
#include <QFileDialog>
#include <QStandardPaths>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>

RatingViewWidget::RatingViewWidget(QWidget *parent)
    : QWidget(parent)
    , m_ratingManager(nullptr)
    , m_mainLayout(nullptr)
    , m_filterGroup(nullptr)
    , m_filterLayout(nullptr)
    , m_searchEdit(nullptr)
    , m_ratingFilter(nullptr)
    , m_startDateEdit(nullptr)
    , m_endDateEdit(nullptr)
    , m_refreshButton(nullptr)
    , m_exportButton(nullptr)
    , m_ratingTable(nullptr)
    , m_searchTimer(nullptr)
    , m_refreshTimer(nullptr)
    , m_isRefreshing(false)
{
    setupUI();
    setupConnections();
    applyStyles();
    
    // 初始化搜索定时器
    m_searchTimer = new QTimer(this);
    m_searchTimer->setSingleShot(true);
    m_searchTimer->setInterval(300); // 300ms防抖
    connect(m_searchTimer, &QTimer::timeout, this, &RatingViewWidget::filterRatingData);
    
    // 初始化刷新定时器，用于防抖刷新
    m_refreshTimer = new QTimer(this);
    m_refreshTimer->setSingleShot(true);
    m_refreshTimer->setInterval(300); // 300ms防抖
    connect(m_refreshTimer, &QTimer::timeout, this, [this]() {
        if (!m_isRefreshing) {
            m_isRefreshing = true;
            refreshData();
            QTimer::singleShot(100, this, [this]() {
                m_isRefreshing = false;
            });
        }
    });
}

RatingViewWidget::~RatingViewWidget()
{
    // Qt会自动清理子对象
}

void RatingViewWidget::setRatingManager(RatingManager *manager)
{
    if (m_ratingManager) {
        // 断开原有连接
        disconnect(m_ratingManager, nullptr, this, nullptr);
    }
    
    m_ratingManager = manager;
    
    if (m_ratingManager) {
        // 连接信号
        connect(m_ratingManager, &RatingManager::ratingCreated,
                this, &RatingViewWidget::onRatingCreated);
        connect(m_ratingManager, &RatingManager::ratingUpdated,
                this, &RatingViewWidget::onRatingUpdated);
        connect(m_ratingManager, &RatingManager::ratingDeleted,
                this, &RatingViewWidget::onRatingDeleted);
        connect(m_ratingManager, &RatingManager::ratingsChanged,
                this, &RatingViewWidget::onRatingsChanged);
        
        // 加载数据
        refreshData();
    }
}

void RatingViewWidget::refreshData()
{
    if (!m_ratingManager) {
        showStatusMessage("评价管理器未初始化", true);
        return;
    }
    
    loadRatingData();
    filterRatingData();
    showStatusMessage("数据已刷新");
}

void RatingViewWidget::setupUI()
{
    // 主布局 - 单列布局，不再使用分割器
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(15, 15, 15, 15);
    m_mainLayout->setSpacing(15);
    
    // 设置筛选控件
    setupFilterControls();
    m_mainLayout->addWidget(m_filterGroup);
    
    // 创建评价表格 - 现在占用全部宽度
    setupRatingTable();
    m_mainLayout->addWidget(m_ratingTable);
}

void RatingViewWidget::setupFilterControls()
{
    m_filterGroup = new QGroupBox("筛选条件");
    m_filterLayout = new QHBoxLayout(m_filterGroup);
    m_filterLayout->setContentsMargins(15, 10, 15, 10);
    m_filterLayout->setSpacing(15);
    
    // 搜索框 - 适配全宽度布局
    QLabel *searchLabel = new QLabel("顾客名:");
    m_searchEdit = new QLineEdit();
    m_searchEdit->setPlaceholderText("搜索顾客用户名(如:sq123)");
    m_searchEdit->setMaximumWidth(200);
    m_searchEdit->setMinimumHeight(32);
    
    // 评分筛选 - 适配全宽度布局
    QLabel *ratingLabel = new QLabel("评分:");
    m_ratingFilter = new QComboBox();
    m_ratingFilter->addItem("全部评分", -1);
    m_ratingFilter->addItem("5星 ★★★★★", 5);
    m_ratingFilter->addItem("4星 ★★★★☆", 4);
    m_ratingFilter->addItem("3星 ★★★☆☆", 3);
    m_ratingFilter->addItem("2星 ★★☆☆☆", 2);
    m_ratingFilter->addItem("1星 ★☆☆☆☆", 1);
    m_ratingFilter->setMaximumWidth(160);
    m_ratingFilter->setMinimumHeight(32);
    
    // 日期筛选 - 适配全宽度布局
    QLabel *dateLabel = new QLabel("日期:");
    m_startDateEdit = new QDateEdit();
    m_startDateEdit->setDate(QDate::currentDate().addDays(-30));
    m_startDateEdit->setCalendarPopup(true);
    m_startDateEdit->setMaximumWidth(130);
    m_startDateEdit->setMinimumHeight(32);
    
    QLabel *toLabel = new QLabel("至");
    m_endDateEdit = new QDateEdit();
    m_endDateEdit->setDate(QDate::currentDate());
    m_endDateEdit->setCalendarPopup(true);
    m_endDateEdit->setMaximumWidth(130);
    m_endDateEdit->setMinimumHeight(32);
    
    // 操作按钮 - 适配全宽度布局
    m_refreshButton = new QPushButton("刷新");
    m_refreshButton->setMaximumWidth(90);
    m_refreshButton->setMinimumHeight(36);
    m_exportButton = new QPushButton("导出");
    m_exportButton->setMaximumWidth(90);
    m_exportButton->setMinimumHeight(36);
    
    // 添加到布局
    m_filterLayout->addWidget(searchLabel);
    m_filterLayout->addWidget(m_searchEdit);
    m_filterLayout->addWidget(ratingLabel);
    m_filterLayout->addWidget(m_ratingFilter);
    m_filterLayout->addWidget(dateLabel);
    m_filterLayout->addWidget(m_startDateEdit);
    m_filterLayout->addWidget(toLabel);
    m_filterLayout->addWidget(m_endDateEdit);
    m_filterLayout->addWidget(m_refreshButton);
    m_filterLayout->addWidget(m_exportButton);
    m_filterLayout->addStretch();
}

void RatingViewWidget::setupRatingTable()
{
    m_ratingTable = new QTableWidget(this);
    m_ratingTable->setColumnCount(COL_COUNT);
    
    // 设置表头
    QStringList headers = {"ID", "顾客", "订单", "评分", "评价内容", "评价时间"};
    m_ratingTable->setHorizontalHeaderLabels(headers);
    
    // 表格设置
    m_ratingTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_ratingTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_ratingTable->setAlternatingRowColors(true);
    m_ratingTable->setSortingEnabled(true);
    m_ratingTable->setContextMenuPolicy(Qt::CustomContextMenu);
    m_ratingTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    // 设置表格行高和字体 - 增加行高让表格更舒适
    m_ratingTable->verticalHeader()->setDefaultSectionSize(35);
    m_ratingTable->verticalHeader()->hide();
    
    // 列宽设置
    QHeaderView *header = m_ratingTable->horizontalHeader();
    header->setSectionResizeMode(COL_ID, QHeaderView::Fixed);
    header->setSectionResizeMode(COL_CUSTOMER, QHeaderView::Fixed);
    header->setSectionResizeMode(COL_ORDER, QHeaderView::Fixed);
    header->setSectionResizeMode(COL_RATING, QHeaderView::Fixed);
    header->setSectionResizeMode(COL_COMMENT, QHeaderView::Stretch);
    header->setSectionResizeMode(COL_DATE, QHeaderView::Fixed);
    
    // 设置固定列宽 - 适配全宽度布局
    m_ratingTable->setColumnWidth(COL_CUSTOMER, 100);
    m_ratingTable->setColumnWidth(COL_ORDER, 120);
    m_ratingTable->setColumnWidth(COL_RATING, 100);
    m_ratingTable->setColumnWidth(COL_DATE, 140);
    
    // 隐藏ID列
    m_ratingTable->setColumnHidden(COL_ID, true);
}





void RatingViewWidget::setupConnections()
{
    // 筛选控件
    connect(m_searchEdit, &QLineEdit::textChanged, this, [this]() {
        m_searchTimer->stop();
        m_searchTimer->start();
    });
    connect(m_ratingFilter, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &RatingViewWidget::onRatingFilterChanged);
    connect(m_startDateEdit, &QDateEdit::dateChanged,
            this, &RatingViewWidget::onDateFilterChanged);
    connect(m_endDateEdit, &QDateEdit::dateChanged,
            this, &RatingViewWidget::onDateFilterChanged);
    connect(m_refreshButton, &QPushButton::clicked,
            this, &RatingViewWidget::onRefreshClicked);
    connect(m_exportButton, &QPushButton::clicked,
            this, &RatingViewWidget::onExportClicked);
    
    // 表格操作
    connect(m_ratingTable, &QTableWidget::cellDoubleClicked,
            this, &RatingViewWidget::onTableItemDoubleClicked);
}

void RatingViewWidget::applyStyles()
{
    setStyleSheet(R"(
        RatingViewWidget {
            background-color: #f8f9fa;
            font-size: 12px;
        }
        
        QGroupBox {
            font-weight: bold;
            border: 2px solid #bdc3c7;
            border-radius: 8px;
            margin: 5px 0px;
            padding-top: 15px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 5px 0 5px;
            color: #2c3e50;
        }
        
        QTableWidget {
            gridline-color: #e0e0e0;
            background-color: white;
            selection-background-color: #3498db;
            selection-color: white;
            border: 1px solid #bdc3c7;
            border-radius: 3px;
            font-size: 11px;
        }
        
        QTableWidget::item {
            padding: 8px 10px;
            border-bottom: 1px solid #ecf0f1;
        }
        
        QTableWidget::item:selected {
            background-color: #3498db;
            color: white;
        }
        
        QTableWidget QHeaderView::section {
            background-color: #34495e;
            color: white;
            padding: 5px;
            border: none;
            font-weight: bold;
            font-size: 11px;
        }
        
        QLineEdit, QComboBox, QDateEdit {
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            padding: 6px 10px;
            background-color: white;
            font-size: 12px;
            min-height: 24px;
        }
        
        QLineEdit:focus, QComboBox:focus, QDateEdit:focus {
            border-color: #3498db;
        }
        
        QTextEdit {
            border: 1px solid #bdc3c7;
            border-radius: 3px;
            padding: 4px;
            background-color: white;
            font-size: 11px;
        }
        
        QTextEdit:focus {
            border-color: #3498db;
        }
        
        QPushButton {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            font-weight: bold;
            font-size: 12px;
            min-height: 28px;
        }
        
        QPushButton:hover {
            background-color: #2980b9;
        }
        
        QPushButton:pressed {
            background-color: #21618c;
        }
        
        QPushButton:disabled {
            background-color: #bdc3c7;
            color: #7f8c8d;
        }
        
        QPushButton[objectName="deleteButton"] {
            background-color: #e74c3c;
        }
        
        QPushButton[objectName="deleteButton"]:hover {
            background-color: #c0392b;
        }
        
        QLabel {
            color: #2c3e50;
            font-size: 12px;
            padding: 2px;
        }
        
        QFrame[frameShape="4"] {
            color: #bdc3c7;
        }
    )");
}

void RatingViewWidget::loadRatingData()
{
    if (!m_ratingManager) return;
    
    m_allRatings = m_ratingManager->getAllRatings();
    showStatusMessage(QString("已加载 %1 条评价").arg(m_allRatings.size()));
}

void RatingViewWidget::updateRatingTable()
{
    m_ratingTable->setSortingEnabled(false);
    m_ratingTable->setRowCount(m_filteredRatings.size());
    
    for (int row = 0; row < m_filteredRatings.size(); ++row) {
        const Rating &rating = m_filteredRatings.at(row);
        
        // ID (隐藏列)
        m_ratingTable->setItem(row, COL_ID, new QTableWidgetItem(rating.id));
        
        // 顾客
        m_ratingTable->setItem(row, COL_CUSTOMER, new QTableWidgetItem(rating.customerName));
        
        // 订单
        m_ratingTable->setItem(row, COL_ORDER, new QTableWidgetItem(rating.orderId));
        
        // 评分
        QString ratingText = QString("%1 %2").arg(rating.rating).arg(formatRatingStars(rating.rating));
        QTableWidgetItem *ratingItem = new QTableWidgetItem(ratingText);
        ratingItem->setTextAlignment(Qt::AlignCenter);
        m_ratingTable->setItem(row, COL_RATING, ratingItem);
        
        // 评价内容
        QString comment = rating.comment;
        if (comment.length() > 50) {
            comment = comment.left(47) + "...";
        }
        m_ratingTable->setItem(row, COL_COMMENT, new QTableWidgetItem(comment));
        
        // 评价时间
        QString dateText = formatDateTime(rating.createdDate);
        m_ratingTable->setItem(row, COL_DATE, new QTableWidgetItem(dateText));
    }
    
    m_ratingTable->setSortingEnabled(true);
    
    // 更新状态
    showStatusMessage(QString("显示 %1 条评价").arg(m_filteredRatings.size()));
}



void RatingViewWidget::filterRatingData()
{
    RatingSearchCriteria criteria = buildSearchCriteria();
    
    if (!criteria.hasFilters()) {
        m_filteredRatings = m_allRatings;
    } else {
        m_filteredRatings.clear();
        for (const Rating &rating : m_allRatings) {
            bool matches = true;
            
            // 顾客名搜索
            if (!criteria.customerName.isEmpty()) {
                if (!rating.customerName.contains(criteria.customerName, Qt::CaseInsensitive)) {
                    matches = false;
                }
            }
            
            // 评分筛选 - 只有在明确设置了评分范围时才进行筛选
            if (criteria.minRating >= 1 && criteria.maxRating >= 1) {
                if (rating.rating < criteria.minRating || rating.rating > criteria.maxRating) {
                    matches = false;
                }
            }
            
            // 日期筛选
            if (criteria.startDate.isValid() && rating.createdDate < criteria.startDate) {
                matches = false;
            }
            if (criteria.endDate.isValid() && rating.createdDate > criteria.endDate) {
                matches = false;
            }
            
            if (matches) {
                m_filteredRatings.append(rating);
            }
        }
    }
    
    updateRatingTable();
}



void RatingViewWidget::showStatusMessage(const QString &message, bool isError)
{
    emit statusMessageChanged(message, isError ? 0 : 3000);
}

int RatingViewWidget::getSelectedRowIndex()
{
    return m_ratingTable->currentRow();
}

QString RatingViewWidget::getSelectedRatingId()
{
    int row = getSelectedRowIndex();
    if (row >= 0 && row < m_ratingTable->rowCount()) {
        QTableWidgetItem *item = m_ratingTable->item(row, COL_ID);
        return item ? item->text() : QString();
    }
    return QString();
}

void RatingViewWidget::selectRating(const QString &ratingId)
{
    for (int row = 0; row < m_ratingTable->rowCount(); ++row) {
        QTableWidgetItem *item = m_ratingTable->item(row, COL_ID);
        if (item && item->text() == ratingId) {
            m_ratingTable->selectRow(row);
            break;
        }
    }
}

RatingSearchCriteria RatingViewWidget::buildSearchCriteria()
{
    RatingSearchCriteria criteria;
    
    criteria.customerName = m_searchEdit->text().trimmed();
    
    int selectedRating = m_ratingFilter->currentData().toInt();
    if (selectedRating > 0) {
        criteria.minRating = selectedRating;
        criteria.maxRating = selectedRating;
    }
    
    criteria.startDate = m_startDateEdit->date().startOfDay();
    criteria.endDate = m_endDateEdit->date().addDays(1).startOfDay(); // 包含结束日期当天
    
    return criteria;
}

QString RatingViewWidget::formatRatingStars(int rating)
{
    if (rating < 1 || rating > 5) {
        return "";
    }
    
    QString stars;
    for (int i = 1; i <= 5; ++i) {
        if (i <= rating) {
            stars += "★";
        } else {
            stars += "☆";
        }
    }
    return stars;
}

QString RatingViewWidget::formatDateTime(const QDateTime &dateTime)
{
    if (!dateTime.isValid()) {
        return "-";
    }
    return dateTime.toString("yyyy-MM-dd hh:mm");
}

// 槽函数实现
void RatingViewWidget::onRatingCreated(const Rating &rating)
{
    Q_UNUSED(rating)
    // 使用防抖定时器避免频繁刷新导致死锁
    if (m_refreshTimer && !m_isRefreshing) {
        m_refreshTimer->start();
    }
}

void RatingViewWidget::onRatingUpdated(const QString &ratingId, const Rating &oldRating, const Rating &newRating)
{
    Q_UNUSED(ratingId)
    Q_UNUSED(oldRating)
    Q_UNUSED(newRating)
    // 使用防抖定时器避免频繁刷新导致死锁
    if (m_refreshTimer && !m_isRefreshing) {
        m_refreshTimer->start();
    }
}

void RatingViewWidget::onRatingDeleted(const QString &ratingId)
{
    Q_UNUSED(ratingId)
    // 使用防抖定时器避免频繁刷新导致死锁
    if (m_refreshTimer && !m_isRefreshing) {
        m_refreshTimer->start();
    }
}

void RatingViewWidget::onRatingsChanged()
{
    // 使用防抖定时器避免频繁刷新导致死锁
    if (m_refreshTimer && !m_isRefreshing) {
        m_refreshTimer->start();
    }
}



void RatingViewWidget::onSearchTextChanged()
{
    // 由定时器处理，防抖
}

void RatingViewWidget::onRatingFilterChanged()
{
    filterRatingData();
}

void RatingViewWidget::onDateFilterChanged()
{
    filterRatingData();
}

void RatingViewWidget::onRefreshClicked()
{
    refreshData();
}

void RatingViewWidget::onExportClicked()
{
    QString fileName = QFileDialog::getSaveFileName(
        this,
        "导出评价数据",
        "ratings_export.json",
        "JSON文件 (*.json);;所有文件 (*)"
    );
    
    if (fileName.isEmpty()) {
        return;
    }
    
    // 导出当前筛选的评价数据
    QJsonArray ratingsArray;
    for (const Rating &rating : m_filteredRatings) {
        ratingsArray.append(rating.toJson());
    }
    
    QJsonObject exportData;
    exportData["exportDate"] = QDateTime::currentDateTime().toString(Qt::ISODate);
    exportData["totalCount"] = m_filteredRatings.size();
    exportData["ratings"] = ratingsArray;
    
    QJsonDocument doc(exportData);
    
    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly)) {
        file.write(doc.toJson());
        file.close();
        showStatusMessage(QString("评价数据已导出到: %1").arg(fileName));
    } else {
        showStatusMessage("导出失败: 无法写入文件", true);
    }
}



void RatingViewWidget::onTableItemDoubleClicked(int row, int column)
{
    Q_UNUSED(row)
    Q_UNUSED(column)
    
    // 双击显示完整评价内容
    QString ratingId = getSelectedRatingId();
    if (ratingId.isEmpty()) {
        return;
    }
    
    for (const Rating &rating : m_filteredRatings) {
        if (rating.id == ratingId) {
            QMessageBox msgBox(this);
            msgBox.setWindowTitle("评价详情");
            msgBox.setTextFormat(Qt::RichText);
            msgBox.setText(QString(
                "<b>顾客:</b> %1<br>"
                "<b>订单:</b> %2<br>"
                "<b>评分:</b> %3 %4<br>"
                "<b>时间:</b> %5<br><br>"
                "<b>评价内容:</b><br>%6"
            ).arg(rating.customerName)
             .arg(rating.orderId)
             .arg(rating.rating)
             .arg(formatRatingStars(rating.rating))
             .arg(formatDateTime(rating.createdDate))
             .arg(rating.comment.isEmpty() ? "无评价内容" : rating.comment));
            msgBox.exec();
            break;
        }
    }
}




